import { ref } from "vue";
import { Order } from "../interface/order.interface";
import { http } from "../http";

export function useOrder() {
  const order = ref({} as Order);

  async function getOrder() {
    if (localStorage.token) {
      order.value = (await http.get("/orders/current")).data;
    }
  }

  async function updateOrderStatus(status: number) {
    await http.patch(`/orders/${order.value._id}`, {
      status,
    });
  }

  async function updateOrder(order: Order) {
    await http.patch(`/orders/${order._id}`, order);
  }

  return {
    order,
    getOrder,
    updateOrderStatus,
    updateOrder,
  };
}

export function useOrders() {
  const orders = ref([] as Order[]);

  async function getOrders(
    status: number | null = null,
    page: number = 1,
    pageSize: number = 5
  ) {
    const res = (
      await http.get("/orders", {
        params: {
          status,
          page,
          pageSize,
        },
      })
    ).data;
    orders.value = res.items;
    orders.value.forEach((i) => {
      i.key = i._id;
    });
    return res.total;
  }

  return {
    orders,
    getOrders,
  };
}
